package com.enterprise.web;

import com.assg2.dao.DaoViewer;
import com.movie.Viewer;
import java.io.*;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * This command is to remove a record from the database
 * @author  yunki
 */
public class RegisterCommand extends HttpServlet implements Command {

    /** Creates a new instance of DeleteCommand */
    public RegisterCommand() {
    }

    public String execute(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        PrintWriter out = response.getWriter();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        response.setContentType("text/html");

//        ServletContext context = getServletContext();
//        
//        context.setAttribute("username", username);
//        context.setAttribute("password", password);
//        context.setAttribute("email", email);
//        


        DaoViewer dv = new DaoViewer();
        Viewer v = (Viewer) dv.findBy("username", username);
        if (v != null) {
            request.setAttribute("message", "Sorry, username has been used <A HREF='register.jsp'>back to register page</A>");
            return "message";
        }

        String usercode = UrlEncode.Encode(username);
        //out.print("<body>");
        String mail = "<b>click the link to finish your regeister:</b><a href='http://localhost:8080/assg2/RegisterCheck?usercode=" + usercode + "'>click</a>";
//        out.print("</body>");
        // out.print(mail);
        SendMail.send(email, mail);
        //  return "/toCheckMail.jsp").include(request, response);
        //return "RequestTransfer";
        request.getRequestDispatcher("RequestTransfer").forward(request, response);



        return null;
    }
}
